let http = require('http'),
	fs = require('fs');

const WEB_PATH = __dirname + '/web',
	PORT = 8282;

let server = http.createServer(function(request, response){
	let url = request.url;
	
	console.log('收到http协议请求，请求地址是：' + url);
	
	if(url === '/'){
		url = '/index.html';
	}
	
	let responseFile = WEB_PATH + url;
	fs.stat(responseFile, (err, stat) => {
		let responseContent = null;
		if(err){
			console.log('该地址无效');
			response.writeHead(404, {
				'Content-type' : 'text/html'
			});
			response.end('嘿嘿，这是你熟悉的404页面 -_- <button type="button" onclick="history.back()">返回上一页</button>');
			return;
		}

		require('fs').readFile(responseFile, 'UTF-8', (err, responseContent) => {
			response.writeHead(200, {
				'Content-type' : 'text/html'
			});
			response.end(responseContent);
		});
	});
});

console.log('server start at port: ' + PORT);
server.listen(PORT, '127.0.0.1');